package com.peaker.advertisingpro.utils

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.ActivityManager.RunningAppProcessInfo
import android.content.Context
import android.content.Context.ACTIVITY_SERVICE
import android.content.Intent
import android.os.Build
import android.os.Handler
import com.peaker.advertisingpro.activity.ScrollActivity
import java.lang.reflect.Method
import java.util.*


/**
 *  @ 作者 CODE_LYF
 *  @ 时间   2021/4/6.
 *  代码人生
 */
object Utils {
    /**
     * 是否运行在前端
     */
    fun isRunningForeground(context: Context): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val appProcessInfos = activityManager.runningAppProcesses
        // 枚举进程
        for (appProcessInfo in appProcessInfos) {
            if (appProcessInfo.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                if (appProcessInfo.processName == context.getApplicationInfo().processName) {
                    return true
                }
            }
        }
        return false
    }

    /**
     * 打开首页
     */
    fun openActivity(context: Context) {
        if (!isRunningForeground(context)) { //获取ActivityManager
            val mAm =
                context.getSystemService(ACTIVITY_SERVICE) as ActivityManager?
            //获得当前运行的task
            val taskList = mAm!!.getRunningTasks(100)
            for (rti in taskList) { //找到当前应用的task，并启动task的栈顶activity，达到程序切换到前台
                if (rti.topActivity.packageName == context.packageName) {
                    mAm.moveTaskToFront(rti.id, 0)
                    return
                }
            }
            //若没有找到运行的task，用户结束了task或被系统释放，则重新启动mainactivity
            val resultIntent = Intent(context, ScrollActivity::class.java)
            resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
            context.startActivity(resultIntent)
        }


    }

    /**
     * 亮度转换
     */
    fun lightTrans(l: Int) = l * 255 / 100

    /**
     * 字符串装任务时间字符串
     */
    fun timeToTaskStr(time: String): String {
        ////（秒、分、时、日、月、周）
        val times = time.split(":")
        return "0 ${times[1]} ${times[0]} * * *"
    }

    fun datebootToTaskStr(timeoff: String): String {
        // var time = "2021-12-02 12:12"
        ////（秒、分、时、日、月、周、年）
        val s1 = timeoff.split(" ")
        var splitDate = s1[0].split("-")
        var splitTime = s1[1].split(":")

//        val s2 = timeOn.split(" ")
//        var splitDate2 = s2[0].split("-")
//        var splitTime2 = s2[1].split(":")

        return "0 ${splitTime[1]} ${splitTime[0]} ${splitDate[2]} ${splitDate[1]} ? ${splitDate[0]}"
    }


    fun weekbootToTaskStr(timeoff: String): String {
        // var time = "2021-12-02 12:12"
        ////（秒、分、时、日、月、周、年）
        val s1 = timeoff.split(" ")
        var splitDate = s1[0].split("-")
        var splitTime = s1[1].split(":")

//        val s2 = timeOn.split(" ")
//        var splitDate2 = s2[0].split("-")
//        var splitTime2 = s2[1].split(":")

        return "0 ${splitTime[1]} ${splitTime[0]} ${splitDate[2]} ${splitDate[1]} ? ${splitDate[0]}"
    }

    /**
     * 获取设备唯一ID
     * @return
     */
    @SuppressLint("MissingPermission")
    fun getUUID(): String? {
        var serial: String? = null
        val m_szDevIDShort =
            "35" + Build.BOARD.length % 10 + Build.BRAND.length % 10 + Build.CPU_ABI.length % 10 + Build.DEVICE.length % 10 + Build.DISPLAY.length % 10 + Build.HOST.length % 10 + Build.ID.length % 10 + Build.MANUFACTURER.length % 10 + Build.MODEL.length % 10 + Build.PRODUCT.length % 10 + Build.TAGS.length % 10 + Build.TYPE.length % 10 + Build.USER.length % 10 //13 位
        try {
            serial = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Build.getSerial()
            } else {
                Build.SERIAL
            }
            //API>=9 使用serial号
            return UUID(m_szDevIDShort.hashCode().toLong(), serial.hashCode().toLong()).toString()
        } catch (exception: Exception) { //serial需要一个初始化
            serial = "serial" // 随便一个初始化
        }
        //使用硬件信息拼凑出来的15位号码
        return UUID(m_szDevIDShort.hashCode().toLong(), serial.hashCode().toLong()).toString()
    }

    /**
     * 将rgba的 颜色转变为16精进制 颜色
     */
    fun fixColor(color: String): String {
        if (color.contains("#")) {
            return color
        }
        var values = color.replace("rgba(", "")
            .replace(" ", "")
            .replace(")", "")
            .split(",")
        var R: String
        var G: String
        var B: String
        var A: String
        A = Integer.toHexString(values[3].toInt()).toUpperCase()
        R = Integer.toHexString(values[0].toInt()).toUpperCase()
        G = Integer.toHexString(values[1].toInt()).toUpperCase()
        B = Integer.toHexString(values[2].toInt()).toUpperCase()
        A = if (A.length == 1) "0$A" else A
        R = if (R.length == 1) "0$R" else R
        G = if (G.length == 1) "0$G" else G
        B = if (B.length == 1) "0$B" else B
        return "#$A$R$G$B"
    }

    /**
     * 处理接收到 的数据
     * 将一个json 根据符号截取
     */
    fun fixJson(json: String): List<String> {
        if (json.isNotEmpty()) {
            var list = json.split(Common.FLAG) as ArrayList
            list.removeAt(list.size - 1)
            return list
        }
        return emptyList()
    }

    /**
     * 处理播放列表的Id
     */
    fun fixListId(ids: String): List<String> = ids.replace("[1-9]+@".toRegex(), "")
        .split(",")


    var handler =Handler()
    fun postDelayed(time:Int,method: ()->Unit){
        handler.postDelayed({
            method()
        },TimeUtil.getLongMs(time))
    }


}